<?php

namespace app\model;

use app\common\controller\PreciseCalculator;
use think\facade\Db;

class MaterialCategoryModel extends BaseModel
{
    protected $name = 'material_category';


    /**
     * Notes: 每天检测自动预警
     * User: chenLei
     * Date: 9/8/25
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkWarning()
    {

        $companyList = CompanyModel::select()->toArray();

        foreach ($companyList as $value) {
            $list = $this->where('warning_quantity', '>', 0)->where('company_id', $value['id'])->select();
            $data = [];
            foreach ($list as $item) {
                if ($item['current_quantity'] <= $item['warning_quantity'] && $item['max_quantity'] > 0 &&
                    $item['max_quantity'] > $item['warning_quantity']) {
                    $data[] = $item->toArray();
                }
            }
            if (count($data) > 0) {
                $res = $this->createPurchase($data, $value['id']);
                if ($res === false) {
                    return $res;
                }
            }

        }

        return true;

    }

    /**
     * Notes:系统自动检测
     * User: chenLei
     * Date: 9/8/25
     * @param $data
     * @return bool
     */

    public function createPurchase($data, $company_id)
    {

        Db::startTrans();
        try {

            $last = PurchaseOrderModel::where('company_id', $company_id)->order('id', 'desc')->find();

            $order_no = 'PO' . date('YmdHis') . rand(1000, 9999);
            $order_data = [
                'order_no' => $order_no,
                'company_id' => $company_id,
                'supplier_id' => $last['supplier_id'] ?? 0,
                'order_date' => date('Y-m-d'),
                'status' => 1,
                'remark' => '系统自动检测，低于预警产品自动生成采购(每日预警)',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'type' => PurchaseOrderModel::TYPE_SYSTEM
            ];
            $order_id = PurchaseOrderModel::insertGetId($order_data);

            $total_amount = 0;
            $order_detail = [];
            foreach ($data as $item) {
                $quantity = $item['max_quantity'] - $item['current_quantity'];

                $amount = PreciseCalculator::mul($item['cost_price'], $quantity);
                $total_amount = PreciseCalculator::add($total_amount, $amount);
                if ($quantity > 0) {
                    $order_detail[] = [
                        'order_id' => $order_id,
                        'material_id' => $item['id'],
                        'quantity' => $quantity,
                        'unit_price' => $item['cost_price'],
                        'amount' => $amount,
                        'delivery_date' => null,
                        'remark' => '系统预警自动生成',
                    ];
                }
            }

            if (count($order_detail) <= 0) {
                throw new \Exception('没有生成采购单');
            }
            PurchaseOrderDetailModel::insertAll($order_detail);
            PurchaseOrderModel::where('id', $order_id)->update(['total_amount' => $total_amount]);

            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;

    }


    /**
     * Notes: 销售订单物料不足情况 自动生成 采购订单
     * User: chenLei
     * Date: 9/16/25
     * @param $params
     * @return bool
     */
    public function bomListCg($params, $company_id)
    {
        Db::startTrans();
        try {

            $order_no = 'PO' . date('YmdHis') . rand(1000, 9999);
            $order_data = [
                'company_id' => $company_id,
                'order_no' => $order_no,
                'supplier_id' => 0,
                'order_date' => date('Y-m-d'),
                'status' => 1,
                'remark' => '销售订单不足，自动生成采购订单(订单审核)',
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'type' => PurchaseOrderModel::TYPE_SYSTEM
            ];
            $order_id = PurchaseOrderModel::insertGetId($order_data);

            $total_amount = 0;
            $order_detail = [];
            foreach ($params as $item) {
                $quantity = $item['diff'];
                $unit_price = $item['cost_price'];
                $amount = PreciseCalculator::mul($unit_price, $quantity);
                $total_amount = PreciseCalculator::add($total_amount, $amount);
                $order_detail[] = [
                    'order_id' => $order_id,
                    'material_id' => $item['material_id'],
                    'quantity' => $quantity,
                    'unit_price' => $unit_price,
                    'amount' => $amount,
                    'delivery_date' => null,
                    'remark' => '销售订单不足，自动生成采购订单',
                ];

            }

            if (count($order_detail) <= 0) {
                throw new \Exception('没有生成采购单');
            }
            PurchaseOrderDetailModel::insertAll($order_detail);
            PurchaseOrderModel::where('id', $order_id)->update(['total_amount' => $total_amount]);


            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error = $exception->getMessage();
            return false;
        }

        return true;
    }


    /**
     * Notes: 库存更新
     * User: chenLei
     * Date: 10/23/25 15:50:40
     * @param $id
     * @param $number
     * @param $memo
     * @param $related_id
     * @param $type
     * @return bool
     */
    public function stockInOut($id, $number, $memo = '', $related_id = 0, $type = 200)
    {
        $info = $this->where('id', $id)->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '物料不存在';
            return false;
        }

        // 根据类型调整数量（100为减少，200为增加）
        if ($type == 100) {
            $number = -$number;
        }

        $before = $info->current_quantity;
        $after = $before + $number;

        // 更新库存数量
        $info->current_quantity = $after;
        $info->save();

        // 记录日志
        $log = [
            'related_id' => $related_id,
            'material_id' => $id,
            'number' => $number,
            'before' => $before,
            'after' => $after,
            'type' => $type,
            'memo' => $memo,
        ];

        (new MaterialLogModel())->save($log);

        return true;
    }


    public function stockInOutProduct($id, $number, $memo = '', $related_id = 0, $type = 200)
    {
        $info = ProductModel::where('id', $id)->findOrEmpty();
        if ($info->isEmpty()) {
            $this->error = '产品不存在';
            return false;
        }

        // 根据类型调整数量（100为减少，200为增加）
        if ($type == 100) {
            $number = -$number;
        }

        $before = $info->current_quantity;
        $after = $before + $number;

        // 更新库存数量
        $info->current_quantity = $after;
        $info->save();

        // 记录日志
        $log = [
            'related_id' => $related_id,
            'product_id' => $id,
            'number' => $number,
            'before' => $before,
            'after' => $after,
            'type' => $type,
            'memo' => $memo,
        ];

        (new MaterialLogModel())->save($log);

        return true;
    }
}